﻿using System;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.SettingsPart
{
    public partial class ViewLog : System.Web.UI.Page
    {
        private const string LogsDataSourceKey = "ProjectsDataSourceKey";

        private bool IsAdmin
        {
            get
            {
                return Session[SiteMaster.IsAdminKey] != null && (bool)Session[SiteMaster.IsAdminKey]; 
            }
        }

        public DataTable LogsListData
        {
            get
            {
                return ViewState[LogsDataSourceKey] != null
                           ? (DataTable)ViewState[LogsDataSourceKey]
                           : (DataTable)(ViewState[LogsDataSourceKey] = SiteMaster.Proxy.GetLogsList());
            }

            set { ViewState[LogsDataSourceKey] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            grdLogsList.DataSource = LogsListData;
            grdLogsList.DataBind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            
            Rebind();

            btnClearLogs.Enabled = grdLogsList.Rows.Count > 0 && IsAdmin;            
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Remove":
                    {
                        ClearLogs();

                        break;
                    }
            }
        }

        private void ClearLogs()
        {
            SiteMaster.Proxy.ClearLogs();

            LogsListData = null;
        }
    }
}